package com.qingzhou.web.service.impl.convert;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.fastjson2.JSON;
import com.mybatisflex.core.query.QueryWrapper;
import com.qingzhou.system.domain.SysDictData;
import com.qingzhou.system.service.ISysDictDataService;
import com.qingzhou.web.service.util.DictUtil;
import org.noear.solon.Solon;

import java.util.List;
import java.util.stream.Collectors;

public class DictConverter implements Converter<String> {
    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {

        WriteCellData<Object> emptyData = new WriteCellData<>("");
        emptyData.setType(CellDataTypeEnum.STRING);
        if(StrUtil.isEmpty(value)) {
            return emptyData;
        }

        ISysDictDataService dictDataService = Solon.context().getBean(ISysDictDataService.class);
        SysDictData condition = new SysDictData();
        condition.setDictValue(value);

        // 获取字段上的@DictParent注解，获取里面的字典父级编码值
        DictParent dictParent = contentProperty.getField().getAnnotation(DictParent.class);

        boolean typeJSONArray = JSONUtil.isTypeJSONArray(value);
        if(typeJSONArray){
            List<String> strList = JSON.parseArray(value, String.class);
            List<String> collect = strList.stream().map(item -> DictUtil.getLabel(item, dictParent.value())).collect(Collectors.toList());
            return new WriteCellData<>(CollUtil.join(collect,"、"));
        }

        SysDictData dictData = null;
        if(ObjUtil.isNotNull(dictParent)){
            String parentCode = dictParent.value();
            condition.setDictType(parentCode);
            dictData = dictDataService.getMapper().selectOneByQuery(QueryWrapper.create(condition));
        }else{
            dictData = dictDataService.getMapper().selectOneByQuery(QueryWrapper.create(condition));
        }
        if(ObjUtil.isNull(dictData)) return new WriteCellData<>(value);
        return new WriteCellData<>(dictData.getDictLabel());
    }
}
